package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author xin Zhou
 * @since 2024-01-16
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


//    一级元素的表单信息
    @Override
    /*
      Cacheable 用于读取数据
      CachePut  用于保存数据
      CachePut  用于更改和删除数据
    * */
    @Cacheable(value="getChildListByPid",key = "'selectIndexList'+#pid")
    public List<Dict> getChildListByPid(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
//            如果有子元素的话HasChildren的值设置为true
            dict.setHasChildren(isHasChildren(dict.getId()));
        }
        return dicts;
    }

    @Override
    public void downlaod(HttpServletResponse response) throws IOException {
        List<Dict> list = baseMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>(list.size());
        for (Dict dict :list){
            DictEeVo dictEeVo = new DictEeVo();

//            把原对象的属性值,赋值给目标对象的属性上
//            要求: 原对象和目标对象对应的属性名相同
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVoList.add(dictEeVo);
        }
//        下载设置响应头信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                .sheet("学生列表1")
                .doWrite(dictEeVoList);
    }

//    因为是自主上传的文件,所以可以转化为输入流
    @Override
//    上传文件的时候对数据库进行清空 再次请求客户端进行刷新
//    否则更新的数据注入不进redis缓存
    @CacheEvict(value = "getChildListByPid",allEntries = true)
    public void upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet(0).doRead();
    }

//    根据Id属性值查询字符串信息
    @Override
    public String getNameByValue(Long value) {
        String result= null;

//        Mybatis-plus
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value",value);
        Dict resultObj = baseMapper.selectOne(queryWrapper);
        if (resultObj != null){
            result = resultObj.getName();
        }

        return result;
    }

//    根据医院的等级编号获取医院的等级信息
    @Override
    public String getNameByDictcodeAndValue(String dictCode, Long value) {
        /*
        * 思路:
        *   首先先通过dictCode获取到Id
        *   然后把Id 当成parentId和value进行联合查询
        *   最后得到医院的等级信息
        * */

//        通过
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);

        Long id = dict.getId();
        QueryWrapper<Dict> query = new QueryWrapper<>();
        query.eq("parent_id",id);
        query.eq("value",value);
        return baseMapper.selectOne(query).getName();
//        return "自定义返回值";
    }

//    跟上边的那个一样,获取到医院的名称
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if(StringUtils.isEmpty(parentDictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        } else {
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            if(null == parentDict) return "";
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id",
                    parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        return dictList;
    }


    //实现方法 根据dict_code查询
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    private boolean isHasChildren(Long pid){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);

//        查询parent_id 符合pid的个数
        Integer count = baseMapper.selectCount(queryWrapper);
        return count >0;
    }
}
